﻿package com.toncen.samepms.system.dao;

import java.util.List;

import com.toncen.samepms.common.AbstractDao;
import com.toncen.samepms.common.AbstractJob;
import com.toncen.samepms.system.domain.SchedulerJob;
import com.sky.common.quartz.QuartzManager;

/**
 * 描述：计划任务表SYSTEM_SCHEDULER_JOB的dao文件
 * 
 * @author tch
 */
public class SchedulerJobDao extends AbstractDao<SchedulerJob> {

	public SchedulerJobDao() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.comit.common.db.BaseDao#initialize()
	 */
	@Override
	protected void initialize() {
		setStatementPrefix("SchedulerJob");
		setStatementDivision(".");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.toncen.samepms.common.AbstractDao#add(com.toncen.samepms.common.AbstractDomain)
	 */
	@Override
	public long add(SchedulerJob domain) throws Exception {
		long id = super.add(domain);
		restartScheduler();
		return id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.toncen.samepms.common.AbstractDao#delete(long)
	 */
	@Override
	public int delete(long id) throws Exception {
		int count = super.delete(id);
		restartScheduler();
		return count;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.toncen.samepms.common.AbstractDao#update(com.toncen.samepms.common.AbstractDomain)
	 */
	@Override
	public int update(SchedulerJob domain) throws Exception {
		int count = super.update(domain);
		restartScheduler();
		return count;
	}

	/**
	 * 根据状态获取
	 * 
	 * @param state
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public List<SchedulerJob> getByState(int state) throws Exception {
		return findList("getByState", state);
	}

	/**
	 * @throws Exception
	 */
	public void restartScheduler() throws Exception {
		QuartzManager.shutdown();
		logger.info("开始启动计划任务...");
		List<SchedulerJob> schedulerJobList = this.getByState(1);
		AbstractJob job;
		for (SchedulerJob schedulerJob : schedulerJobList) {
			try {
				job = schedulerJob.getJob();
				QuartzManager.addJob(schedulerJob.getJobName(), job, schedulerJob.getTime());
				logger.info("添加计划任务【" + schedulerJob.getJobName() + "】...");
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("添加计划任务【" + schedulerJob.getJobName() + "】失败：" + e.getMessage());
			}
		}
		logger.info("成功启动计划任务...");
	}

	/**
	 * 立即执行计划任务
	 * 
	 * @param schedulerJob
	 * @throws Exception
	 */
	public void immediatelyRun(SchedulerJob schedulerJob) throws Exception {
		logger.info("开始立即执行计划任务...");
		try {
			AbstractJob job = schedulerJob.getJob();
			QuartzManager.addJob(schedulerJob.getJobName(), job, schedulerJob.getTime());
			QuartzManager.triggerJob(schedulerJob.getJobName());// 立即执行一次
			logger.info("添加计划任务【" + schedulerJob.getJobName() + "】...");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加计划任务【" + schedulerJob.getJobName() + "】失败：" + e.getMessage());
		}
		logger.info("成功立即执行计划任务...");
	}
}
